using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Drawing.Drawing2D;
using System.Globalization;
using QuickLaunch.Properties;

namespace QuickLaunch
{
    public partial class AutoCompleteForm : Form
    {
        #region Const settings

        const int topNResults = 7;

        #endregion

        private SearchBoxForm searchBoxForm = null;

        public AutoCompleteForm(SearchBoxForm searchBoxForm)
        {
            InitializeComponent();
            this.searchBoxForm = searchBoxForm;
            this.list_AutoComplete.SmallImageList = this.fileSystemImageList1.SmallImageList;

            // register the form in the form manager
            Program.formManager.AddForm(this);
        }

        #region Public methods

        /// <summary>
        /// List items in the autocomplete list according to the search result of the query.
        /// </summary>
        /// <param name="query"></param>
        public void ListItems(string query)
        {
            Program.fileNameSearch.Query = query.ToLower();
            // get the search result list.
            List<FileSearchResult> results = Program.fileNameSearch.Search();
            // we only need the top n
            int neededResultCount = results.Count >= topNResults ? topNResults : results.Count;
            
            // clear the auto-complete list.
            this.list_AutoComplete.Items.Clear();
            // bind the search result to the listview control
            // add the items from the end to top
            int actualHeight = 0;
            for (int i = results.Count - 1; i >= results.Count - neededResultCount; i--)
            {
                FileSearchResult result = results[i];

                // add the image icon column
                int imageId = this.fileSystemImageList1.GetTheFileIconIndex(result.FileName);
                ListViewItem item = this.list_AutoComplete.Items.Add("", imageId);

                // add the file name column
                item.SubItems.Add(result.FileName);

                // add the file path column
                item.SubItems.Add(FileNameHelper.Shorten(result.FilePath), 
                    Color.Green, Color.Transparent, this.list_AutoComplete.Font);
                
                item.ToolTipText = result.FilePath;
                
                actualHeight += item.Bounds.Height;
            }

            // select the first item by default.
            if (this.list_AutoComplete.Items.Count > 0)
                this.list_AutoComplete.Items[0].Selected = true;

            // make sure that the control is visible
            if (!this.Visible)
                this.Visible = true;

            // adjust the form size according to the search result
            this.list_AutoComplete.Height = actualHeight;
            this.Height = actualHeight + this.list_AutoComplete.Location.Y + 5;
        }

        /// <summary>
        /// Select an item in the autocomplete list according to the specified relative 
        /// position to the current selected index.
        /// </summary>
        /// <param name="relPos"></param>
        public void SelectItem(int relPos)
        {
            if (this.list_AutoComplete.Items.Count <= 0)
                return;

            // if there is already one item selected:
            if (this.list_AutoComplete.SelectedIndices.Count > 0)
            {
                // get the current selected index
                int selectedIndex = this.list_AutoComplete.SelectedIndices[0] + relPos;
                while (selectedIndex < 0)
                    selectedIndex += this.list_AutoComplete.Items.Count;
                selectedIndex %= this.list_AutoComplete.Items.Count;
                this.list_AutoComplete.Items[selectedIndex].Selected = true;
            }
            else // otherwise (if no item is selected)
            {
                // selected the first or the last item according to the relPos
                if (relPos >= 0)
                    this.list_AutoComplete.Items[0].Selected = true;
                else
                    this.list_AutoComplete.Items[this.list_AutoComplete.Items.Count - 1].Selected = true;
            }
        }

        /// <summary>
        /// Get the currently selected item in the autocomplete list
        /// </summary>
        /// <returns></returns>
        public string GetSelectedItem()
        {
            // if no item is selected in the list, return null.
            if (this.list_AutoComplete.SelectedItems.Count <= 0)
                return null;
            
            // return the full file name
            return this.list_AutoComplete.SelectedItems[0].ToolTipText;
        }

        #endregion

        #region Form Event Handlers

        private static Color borderColor = Color.FromArgb(128, 128, 128);

        private void AutoCompleteForm_Paint(object sender, PaintEventArgs e)
        {
            // redraw the form border.
            ControlPaint.DrawBorder(e.Graphics, this.ClientRectangle, borderColor, ButtonBorderStyle.Solid);
        }

        /// <summary>
        /// Occurs when users hovers over the list view
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void list_AutoComplete_ItemMouseHover(object sender, ListViewItemMouseHoverEventArgs e)
        {
            // select the item
            e.Item.Selected = true;
        }

        /// <summary>
        /// handle the DrawSubItem event to draw elements for individual subitems, such as text values.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void list_AutoComplete_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)
        {
            switch (e.ColumnIndex)
            {
                // The first column is image column
                case 0: e.DrawDefault = true; break;
                default: e.DrawText(); break;
            }
        }

        /// <summary>
        /// In the details view, you can handle the DrawItem event to draw elements common to all 
        /// subitems, such as the background
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void list_AutoComplete_DrawItem(object sender, DrawListViewItemEventArgs e)
        {
            if (e.Item.Selected)
            {
                // Draw the background for an selected item.
                using (LinearGradientBrush brush =
                    new LinearGradientBrush(e.Bounds, Color.WhiteSmoke,
                    Color.Silver, LinearGradientMode.Vertical))
                {
                    // 3D effect.
                    e.Graphics.FillRectangle(brush, e.Bounds);
                }
            }
        }

        private void list_AutoComplete_MouseDown(object sender, MouseEventArgs e)
        {
            // get the select item
            string fileName = this.GetSelectedItem();
            if (!string.IsNullOrEmpty(fileName) &&
                !Program.fileNameSearch.HitFile(fileName))
            {
                //MessageBox.Show(Resources.Msg_CannotOpenFile);
            }

            this.searchBoxForm.DeactivateSearchBox();
        }

        #endregion
    }
}